package com.ruoyi.project.product.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.framework.web.domain.TreeSelect;
import com.ruoyi.project.product.domain.Category;
import com.ruoyi.project.product.mapper.CategoryMapper;
import com.ruoyi.project.product.service.CategoriesService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class CategoriesServiceImpl implements CategoriesService
{
    @Autowired
    private CategoryMapper categoryMapper;
    
    @Autowired
    private SysRoleMapper roleMapper;

    /**
     * 查询部门管理数据
     * 
     * @param Category 部门信息
     * @return 部门信息集合
     */
    @Override
    public List<Category> selectCategoriesList(Category Category)
    {
        return categoryMapper.selectCategoriesList(Category);
    }
    
    /**
     * 查询部门树结构信息
     * 
     * @param category 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectCategoriesTreeList(Category category)
    {
        List<Category> categoriesses = SpringUtils.getAopProxy(this).selectCategoriesList(category);
        return buildCategoriesTreeSelect(categoriesses);
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param categoriesses 部门列表
     * @return 树结构列表
     */
    @Override
    public List<Category> buildCategoriesTree(List<Category> categoriesses)
    {
        List<Category> returnList = new ArrayList<Category>();
        List<Long> tempList = categoriesses.stream().map(Category::getCategoryId).collect(Collectors.toList());
        for (Category Category : categoriesses)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(Category.getParentId()))
            {
                recursionFn(categoriesses, Category);
                returnList.add(Category);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = categoriesses;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param categoriesses 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildCategoriesTreeSelect(List<Category> categoriesses)
    {
        List<Category> categoryTrees = buildCategoriesTree(categoriesses);
        return categoryTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }


    /**
     * 根据部门ID查询信息
     * 
     * @param CategoriesId 部门ID
     * @return 部门信息
     */
    @Override
    public Category selectCategoriesById(Long CategoriesId)
    {
        return categoryMapper.selectCategoriesById(CategoriesId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     * 
     * @param CategoriesId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenCategoriesById(Long CategoriesId)
    {
        return categoryMapper.selectNormalChildrenCategoriesById(CategoriesId);
    }

    /**
     * 是否存在子节点
     * 
     * @param categoriesId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildBycategoriesId(Long categoriesId)
    {
        int result = categoryMapper.hasChildByCategoriesId(categoriesId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     * 
     * @param CategoriesId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkCategoriesExistUser(Long CategoriesId)
    {
        int result = categoryMapper.checkCategoriesExistUser(CategoriesId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     * 
     * @param Category 部门信息
     * @return 结果
     */
    @Override
    public boolean checkCategoriesNameUnique(Category Category)
    {
        Long CategoriesId = StringUtils.isNull(Category.getCategoryId()) ? -1L : Category.getCategoryId();
        Category info = categoryMapper.checkCategoriesNameUnique(Category.getCategoryName(), Category.getParentId());
        if (StringUtils.isNotNull(info) && info.getCategoryId().longValue() != CategoriesId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验部门是否有数据权限
     * 
     * @param CategoriesId 部门id
     */
    @Override
    public void checkCategoriesDataScope(Long CategoriesId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && StringUtils.isNotNull(CategoriesId))
        {
            Category category = new Category();
            category.setCategoryId(CategoriesId);
            List<Category> categoriesses = SpringUtils.getAopProxy(this).selectCategoriesList(category);
            if (StringUtils.isEmpty(categoriesses))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     * 
     * @param category 部门信息
     * @return 结果
     */
    @Override
    public int insertCategories(Category category)
    {
        Category info = categoryMapper.selectCategoriesById(0L);
        if(Objects.nonNull(info)){
            category.setAncestors(info.getAncestors()+","+category.getParentId());
        }else{
            category.setAncestors(String.valueOf(category.getParentId()));
        }

        return categoryMapper.insertCategories(category);
    }

    /**
     * 修改保存部门信息
     * 
     * @param Category 部门信息
     * @return 结果
     */
    @Override
    public int updateCategories(Category Category)
    {
        Category newParentCategory = categoryMapper.selectCategoriesById(Category.getParentId());
        Category oldCategory = categoryMapper.selectCategoriesById(Category.getCategoryId());
        if (StringUtils.isNotNull(newParentCategory) && StringUtils.isNotNull(oldCategory))
        {
            String newAncestors = newParentCategory.getAncestors() + "," + newParentCategory.getCategoryId();
            String oldAncestors = oldCategory.getAncestors();
            Category.setAncestors(newAncestors);
            updateCategoriesChildren(Category.getCategoryId(), newAncestors, oldAncestors);
        }
        int result = categoryMapper.updateCategories(Category);
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param Category 当前部门
     */
    private void updateParentCategoriesStatusNormal(Category Category)
    {
        String ancestors = Category.getAncestors();
        Long[] CategoriesIds = Convert.toLongArray(ancestors);
        categoryMapper.updateCategoriesStatusNormal(CategoriesIds);
    }

    /**
     * 修改子元素关系
     * 
     * @param CategoriesId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateCategoriesChildren(Long CategoriesId, String newAncestors, String oldAncestors)
    {
        List<Category> children = categoryMapper.selectChildrenCategoriesById(CategoriesId);
        for (Category child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            categoryMapper.updateCategoriesChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     * 
     * @param CategoriesId 部门ID
     * @return 结果
     */
    @Override
    public int deleteCategoriesById(Long CategoriesId)
    {
        return categoryMapper.deleteCategoriesById(CategoriesId);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<Category> list, Category t)
    {
        // 得到子节点列表
        List<Category> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Category tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Category> getChildList(List<Category> list, Category t)
    {
        List<Category> tlist = new ArrayList<Category>();
        Iterator<Category> it = list.iterator();
        while (it.hasNext())
        {
            Category n = (Category) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getCategoryId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Category> list, Category t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
